package com.project.controller;

import com.project.bean.CutPageBean;
import com.project.bean.LinkBean;
import com.project.dao.ILinkDao;
import com.project.service.ILinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("link")
public class LinkController {
    @Autowired
    private ILinkService service;

    @RequestMapping("cutAll")
    public String cutAll(@RequestParam(value = "pageNO", defaultValue = "1") int pageNo) {
        CutPageBean<LinkBean> cutBean = service.cutAll(pageNo);
        String str = "<table border='1' width='80%'>";
        str += "<thead><tr><th>姓名</th><th>生日</th><th>电话</th><th>删除</th></tr></thead>";
        str += "<tbody>";
        for (LinkBean link : cutBean.getList()) {
            str += "<tr><td>" + link.getName() + "</td><td>" + link.getBirthday() + "</td>" +
                    "<td>" + link.getPhone() + "</td><td><a href='/link/del?id=" + link.getId() + "'>" + "删除" + "</a>" +
                    " <a href='/link/find?id="+link.getId() +"'>" + "修改" + "</a>" +
                    "</td></tr>";
        }
        str += "</tbody></table>";
        str += "<a href='/addfrom.html'>添加</a>";
        for (int i = 1; i <= cutBean.getToalPage(); i++) {
            str += "<a href='/link/cutAll?pageNO=" + i + "'>" + i + "</a> ";

        }
        return str;
    }

    @RequestMapping("find")
    private String findById(int id) {
        LinkBean byId = service.findById(id);
        String str = "<form action='update'>";
        str += "名字:<span>" + byId.getName() + "</span><br>";
        str += "生日:<span>" + byId.getBirthday() + "</span><br>";
        str += "电话:<input type='text' name='phone' value='" + byId.getPhone() + "'><br>";
        str += "<input type='hidden' name='id' value='" + byId.getId() + "'><br>";
        str += "<input type='submit' value='修改'></form>";
        return str;
    }

    @RequestMapping("update")
    private String update(int id, String phone) {
        service.update(id, phone);
        return this.cutAll(1);
    }

    @RequestMapping("del")
    public String del(int id) {
        service.del(id);
        return this.cutAll(1);
    }
    @RequestMapping("add")
    public String add(String name, String birthday, String phone) {
        LinkBean link = new LinkBean(name, LocalDate.parse(birthday), phone);
        service.add(link);
        return this.cutAll(1);
    }
    public List<LinkBean> shwoLink(){
        List<LinkBean> list =new ArrayList<>();
        list.add(new LinkBean("丁真",LocalDate.parse("1990-12-12"),"123145678965"));
        return list;
    }
}
